package com.eric.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eric.domain.dto.EquipTransferDto;
import com.eric.domain.dto.EquipTransferPhotoDto;
import com.eric.domain.po.EquipTransfer;
import com.eric.domain.po.EquipTransferPhoto;
import com.eric.domain.po.Equipment;
import com.eric.mapper.EquipTransferMapper;
import com.eric.mapper.EquipmentMapper;
import com.eric.service.*;
import com.eric.utils.FilesDownLoad;
import com.eric.utils.PublicTools;
import com.eric.utils.ServerBASEURL;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.DeleteJoinWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.eric.utils.Constant.PAGE_CURRENT;
import static com.eric.utils.Constant.PAGE_SIZE;


/**
 * <p>
 * 设备转移登记表 服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-03-12
 */
@Service
@RequiredArgsConstructor

//  todo saveOne接口和modify接口需要大改
public class EquipTransferServiceImpl extends MPJBaseServiceImpl<EquipTransferMapper, EquipTransfer> implements IEquipTransferService {

    //  配置encode的前缀
    private final static String ENCODE_PREFIX="EQUIPTRANSFER";
    //   判断当前用户权限的布尔值,用于通过登录用户的权限，选择性地决定是否通过location查询数据
//    private final  boolean ROLE_FLAG=PublicTools.checkLoginRole();

    //    用于创建服务器磁盘的文件夹
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    //    用于做图片文件的文件名
    SimpleDateFormat photoDf = new SimpleDateFormat("yyyyMMdd");

    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Value("${file.location}")
    String fileLocation;

    //    创建用于创建服务器磁盘文件件
    String equipTransferPhotoPath="/equipTransferPhotos";

    //    调用equipTransferPhotoService，用于存储图片
    private final IEquipTransferPhotoService equipTransferPhotoService;

    private final ISysUserService userService;

    //    最后需要操作一下equipment这个表，变更设备的所在地
    private final EquipmentMapper equipmentMapper;

    private final ILocationService locationService;

    //   equipmentService
    private final IEquipmentService equipmentService;


    @Override
    @Transactional
    public SaResult modifyOneService(EquipTransferDto equipTransferDto, MultipartFile[] photoFiles, HttpServletRequest request, String[] photoList) {
        EquipTransferDto equipTransferDtoTrim = checkDto(equipTransferDto);
        if (BeanUtil.isEmpty(equipTransferDtoTrim)) {
            return SaResult.error("对象不能为空！");
        }
        if (equipTransferDtoTrim.getId() == null||equipTransferDtoTrim.getId()<=0){
            return SaResult.error("id值不符合要求");
        }
//       todo 下面两个判断是否需要？？前端是根据get方法，获取到表单对象数据，如果还是重新查询数据库，会造成性能降低
        EquipTransfer one = query().eq("id", equipTransferDtoTrim.getId()).one();
        if (BeanUtil.isEmpty(one)) {
            return SaResult.error("“没有此表单，请核实");
        }
        if(!equipTransferDtoTrim.getEncode().equals(one.getEncode())){
            return SaResult.error("encode和数据库中的encode不匹配");
        }

//     todo   删除前端传进来的文件名的文件，现在策略是不物理删除文件
        if (photoList!=null&& photoList.length>0) {
//            for (String photoUrl : photoList) {
////            1、截取“file/”后面的字符串
//                String substring = photoUrl.substring(photoUrl.indexOf("e") + 2);
////            2、删除文件
//                boolean del = FileUtil.del(fileLocation + substring);
//            }
            equipTransferPhotoService.deleteByPhotoUrlList(Arrays.asList(photoList));
        }

//        把新文件写入数据库
        if (photoFiles!=null) {
            fileOperation(equipTransferDtoTrim.getEncode(), photoFiles, request);
        }
//        获取登录用户id
        Object loginId = StpUtil.getLoginId();
        int userId = Integer.parseInt(loginId.toString());
        String realname = userService.getById(userId).getRealName();
        EquipTransfer equipTransfer = BeanUtil.copyProperties(equipTransferDtoTrim, EquipTransfer.class);
        equipTransfer.setLastUpdateBy(realname);
        updateById(equipTransfer);
        return SaResult.ok("succeed");
    }

    @Override
    @Transactional
    public SaResult deleteOneByIdService(Integer id) {
        if (id == null) {
            return SaResult.error("id不能为空");
        }
//        联表删除
        DeleteJoinWrapper<EquipTransfer>wrapper= JoinWrappers.delete(EquipTransfer.class)
//        删除全部的表数据 (主表和副表)
                .deleteAll()
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                .eq(EquipTransfer::getId,id);
        boolean b = deleteJoin(wrapper);
        return SaResult.ok("succeed");
    }

    @Override
    @Transactional
    public SaResult saveOneByEqId(Integer id,String receivingProject,String description, MultipartFile[] photoFiles, HttpServletRequest request) {
        if (id==null||id<=0){
            return SaResult.error("id值有误");
        }
        Object equipObj = equipmentService.getOneByIdService(id).getData();
        Equipment EquipmentData = BeanUtil.copyProperties(equipObj, Equipment.class);

        if (BeanUtil.isEmpty(EquipmentData)){
            return SaResult.error("根据id查询不到对应的Equipment对象，请核实");
        }
        if (StrUtil.isBlank(receivingProject)){
            return SaResult.error("设备接收地名称不能为空");
        }

        EquipTransferDto equipTransferDto = BeanUtil.copyProperties(EquipmentData, EquipTransferDto.class);
        equipTransferDto.setEquipId(EquipmentData.getId());

        equipTransferDto.setReceivingProject(receivingProject);
        equipTransferDto.setDescription(description);
//        下面四行生成equipTransfer表的Encode
        String encode_suffix = RandomUtil.randomString(5).toUpperCase();
        String dateFormat = photoDf.format(new Date());
        String equipTransfer_encode = ENCODE_PREFIX + dateFormat + encode_suffix;
        equipTransferDto.setEncode(equipTransfer_encode);

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        equipTransferDto.setSendingProject(locationAddress);

//        图片文件存进硬盘中，图片文件地址存进数据库中
        if (photoFiles!=null) {
            boolean b = fileOperation(equipTransfer_encode, photoFiles, request);
        }
//       number永远都是1---这是对应equipMent表中，设备数量永远都是0或者1
        equipTransferDto.setNumber(1);
        EquipTransfer equipTransfer = BeanUtil.copyProperties(equipTransferDto, EquipTransfer.class);

//        通过登录id和userService，获取到用户的realName
        String realname = userService.getById(StpUtil.getLoginId().toString()).getRealName();
//        把获取到的realName设定为表中的Create_by字段
        equipTransfer.setCreateBy(realname);
//        在数据库表中新增一条equipTransfer行
        equipTransfer.setId(null);
        save(equipTransfer);

//        在equipment表中也要执行操作，就是所在地Location=》receivingProject；
//        最后修改人：realname;

        Equipment equipment = BeanUtil.copyProperties(EquipmentData, Equipment.class);
        equipment.setLocation(receivingProject);
        equipment.setLastUpdateBy(realname);

        equipmentMapper.updateById(equipment);
        return SaResult.ok("succeed");
    }

    //    分页获取所有的数据
    @Override
    public SaResult getAllByPage(Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        Page<EquipTransferDto>page=new Page<>(current,pageSize);
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
//        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(records);
    }

    //    匹配分页获取所有数据的count，记住，这个count不是上面分页取得的数据的length，而是全部（不分页）取得的数据行数
    @Override
    public SaResult getAllCountsService() {
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .select( "count(id)")
                .eq(!PublicTools.checkLoginRole(),Equipment::getLocation, locationAddress);
        Long l = selectJoinOne(Long.class, wrapper);
        return SaResult.data(l);
    }

    @Override
    public SaResult getByBetweenTimesService(Date start, Date end, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        if (BeanUtil.isEmpty(start) || BeanUtil.isEmpty(end)) {
            return SaResult.error("日期为空，请核实！");
        }
        if (end.before(start)) {
            Date temp;
            temp=start;
            start=end;
            end=temp;
        }

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        String startFormat = timeFormat.format(start);
        String endFormat = timeFormat.format(end);
        Page<EquipTransferDto>page=new Page<>(current,pageSize);
        //        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .apply("date_format(t.create_time,'%y%m%d') >= date_format('" +startFormat + "','%y%m%d')")
                .apply("date_format(t.create_time,'%y%m%d') <= date_format('" + endFormat + "','%y%m%d')")
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);

    }

    @Override
    public SaResult getOneByIdService(Integer id) {
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .eq(EquipTransfer::getId,id)
                .eq(!PublicTools.checkLoginRole(),Equipment::getLocation, locationAddress)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;


//       拼接图片的url，形成完整的图片路径
        EquipTransferDto equipTransferDto = selectJoinOne(EquipTransferDto.class, wrapper);

        List<EquipTransferPhoto> equipTransferPhotoList = equipTransferDto.getEquipTransferPhotoList();
        if (!BeanUtil.isEmpty(equipTransferPhotoList)){
            for (EquipTransferPhoto equipTransferPhoto : equipTransferPhotoList) {
                String originalUrl = equipTransferPhoto.getPhotoUrl();
                String fullUrl= ServerBASEURL.BASEURL +originalUrl;
                equipTransferPhoto.setPhotoUrl(fullUrl);
            }

        }


        return SaResult.data(equipTransferDto);
    }


    //    根据getByBetweenTimesService这个方法，获取所有数据行的条数
    @Override
    public SaResult getByBetweenTimesCountsService(Date start, Date end) {
        if (BeanUtil.isEmpty(start) || BeanUtil.isEmpty(end)) {
            return SaResult.error("日期为空，请核实！");
        }
        if (end.before(start)) {
            Date tempDate;
            tempDate=start;
            start=end;
            end=tempDate;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        String startFormat = timeFormat.format(start);
        String endFormat = timeFormat.format(end);
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .select("count(id)")
                .apply("date_format(t.create_time,'%y%m%d') >= date_format('" +startFormat + "','%y%m%d')")
                .apply("date_format(t.create_time,'%y%m%d') <= date_format('" + endFormat + "','%y%m%d')")
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
//        Long l = selectJoinCount(wrapper);
        Long l = selectJoinOne(Long.class, wrapper);
        return SaResult.data(l);
    }


    //    多功能查询方法，这里面的name包括设备名、创建人，最后修改人，项目名称
    @Override
    public SaResult getAllByAllTypeName(String name,Integer current,Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(name))){
            return SaResult.error("查询名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }

        Page<EquipTransferDto>page=new Page<>(current,pageSize);
        Set<EquipTransferDto> finalResultList=new HashSet<>();

//        这个是判断当前用户是否已经分配了项目或者仓库，如果没有，返回一个错误
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址，不能查询！");
        }

        //        根据接收地查询
        MPJLambdaWrapper<EquipTransfer>wrapperByReceivingAddrress=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("receiving_project",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapperByReceivingAddrress);
        List<EquipTransferDto> equipTransferDtoList = equipTransferDtoPage.getRecords();
        if (!equipTransferDtoList.isEmpty()){
            finalResultList.addAll(equipTransferDtoList);
        }

//        根据设备名查询
        MPJLambdaWrapper<EquipTransfer>wrapperByEqName=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("eq_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPageByEqName = selectJoinListPage(page, EquipTransferDto.class, wrapperByEqName);
        List<EquipTransferDto> equipTransferDtoListByEqName = equipTransferDtoPageByEqName.getRecords();
        if (!equipTransferDtoListByEqName.isEmpty()){
            finalResultList.addAll(equipTransferDtoListByEqName);
        }

//  根据最后修改人查询

        MPJLambdaWrapper<EquipTransfer>wrapperByLastUpdateBy=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("last_update_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPageByLastUpdateBy = selectJoinListPage(page, EquipTransferDto.class, wrapperByLastUpdateBy);
        List<EquipTransferDto> equipTransferDtoListByLastUpdateBy = equipTransferDtoPageByLastUpdateBy.getRecords();
        if (!equipTransferDtoListByLastUpdateBy.isEmpty()){
            finalResultList.addAll(equipTransferDtoListByLastUpdateBy);
        }
//   根据创建人查询
        MPJLambdaWrapper<EquipTransfer>wrapperByCreateBy=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("create_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPageByCreateBy = selectJoinListPage(page, EquipTransferDto.class, wrapperByCreateBy);
        List<EquipTransferDto> equipTransferDtoListByCreateBy = equipTransferDtoPageByCreateBy.getRecords();
        if (!equipTransferDtoListByCreateBy.isEmpty()){
            finalResultList.addAll(equipTransferDtoListByCreateBy);
        }
//        根据品牌查询

        MPJLambdaWrapper<EquipTransfer>wrapperByBrand=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("brand",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPageByBrand = selectJoinListPage(page, EquipTransferDto.class, wrapperByBrand);
        List<EquipTransferDto> equipTransferDtoListByBrand = equipTransferDtoPageByBrand.getRecords();
        if (!equipTransferDtoListByBrand.isEmpty()){
            finalResultList.addAll(equipTransferDtoListByBrand);
        }


//        根据ENCODE查询
        MPJLambdaWrapper<EquipTransfer>wrapperByEncode=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("encode",name.toUpperCase())
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPageByEncode = selectJoinListPage(page, EquipTransferDto.class, wrapperByEncode);
        List<EquipTransferDto> equipTransferDtoListByEncode = equipTransferDtoPageByEncode.getRecords();
        if (!equipTransferDtoListByEncode.isEmpty()){
            finalResultList.addAll(equipTransferDtoListByEncode);
        }

//        根据设备类型查询
        MPJLambdaWrapper<EquipTransfer>wrapperByTypeName=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("type_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                .groupBy("create_time")
                .orderByDesc(Equipment::getUpdateTime)
//                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
//                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                ;
        Page<EquipTransferDto> equipTransferDtoPageByTypeName = selectJoinListPage(page, EquipTransferDto.class, wrapperByTypeName);
        List<EquipTransferDto> equipTransferDtoListByTypeName = equipTransferDtoPageByTypeName.getRecords();
        if (!equipTransferDtoListByTypeName.isEmpty()){
            finalResultList.addAll(equipTransferDtoListByTypeName);
        }

        List<EquipTransferDto> equipTransferDTOs = new ArrayList<>(finalResultList);

//        对List内部元素重新按照创建时间从晚到早重新排序
        equipTransferDTOs.sort(new Comparator<EquipTransferDto>() {
            @Override
            public int compare(EquipTransferDto o1, EquipTransferDto o2) {
                Date createTime1 = o1.getUpdateTime();
                Date createTime2 = o2.getUpdateTime();
                return createTime2.compareTo(createTime1);
            }
        });
        return SaResult.data(equipTransferDTOs);
    }

    //    配合多功能查询办法，获取所有的数据的条数（不是根据page查询到的数据，二十所有符合要求的数据）
    @Override
    public SaResult getAllByAllTypeNameCounts(String name) {
        if ( StrUtil.isBlank(StrUtil.trim(name))){
            return SaResult.error("查询名不能为空");
        }

        Set<EquipTransfer> finalResultList=new HashSet<>();

//        这个是判断当前用户是否已经分配了项目或者仓库，如果没有，返回一个错误
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址，不能查询！");
        }

        //        根据接收地查询
        MPJLambdaWrapper<EquipTransfer>wrapperByReceivingAddrress=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("receiving_project",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferDtoList = list(wrapperByReceivingAddrress);
        if (!equipTransferDtoList.isEmpty()){
            finalResultList.addAll(equipTransferDtoList);
        }

//        根据设备名查询
        MPJLambdaWrapper<EquipTransfer>wrapperByEqName=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("eq_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferListByEqName = list(wrapperByEqName);
        if (!equipTransferListByEqName.isEmpty()){
            finalResultList.addAll(equipTransferListByEqName);
        }

//  根据最后修改人查询

        MPJLambdaWrapper<EquipTransfer>wrapperByLastUpdateBy=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("last_update_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferListByLastUpdateBy = list(wrapperByLastUpdateBy);
        if (!equipTransferListByLastUpdateBy.isEmpty()){
            finalResultList.addAll(equipTransferListByLastUpdateBy);
        }
//   根据创建人查询
        MPJLambdaWrapper<EquipTransfer>wrapperByCreateBy=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("create_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferListByCreateBy = list(wrapperByCreateBy);
        if (!equipTransferListByCreateBy.isEmpty()){
            finalResultList.addAll(equipTransferListByCreateBy);
        }
//        根据品牌查询

        MPJLambdaWrapper<EquipTransfer>wrapperByBrand=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("brand",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferListByBrand = list(wrapperByBrand);
        if (!equipTransferListByBrand.isEmpty()){
            finalResultList.addAll(equipTransferListByBrand);
        }

//        根据ENCODE查询
        MPJLambdaWrapper<EquipTransfer>wrapperByEncode=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("encode",name.toUpperCase())
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferListByEncode = list(wrapperByEncode);
        if (!equipTransferListByEncode.isEmpty()){
            finalResultList.addAll(equipTransferListByEncode);
        }
//        根据设备类型查询
        MPJLambdaWrapper<EquipTransfer>wrapperByTypeName=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("type_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress);
        List<EquipTransfer> equipTransferListByTypeName = list(wrapperByTypeName);
        if (!equipTransferListByTypeName.isEmpty()){
            finalResultList.addAll(equipTransferListByTypeName);
        }

        List<EquipTransfer> equipTransfers = new ArrayList<>(finalResultList);
        return SaResult.data((long)equipTransfers.size());
    }


    //    文件下载方法
    @Override
    public void downloadFilesService(String[] files, HttpServletResponse response) throws IOException {
        FilesDownLoad.filesToZip(response,files,fileLocation);
    }

    /********************************************下面两个是公用方法***********************************************/

    private EquipTransferDto checkDto(EquipTransferDto equipTransferDto){
//        eqName
        String eqNameTrim = StrUtil.trim(equipTransferDto.getEqName());
        if (StrUtil.isBlank(eqNameTrim)) {equipTransferDto.setEqName(null);}
        else {
            equipTransferDto.setEqName(eqNameTrim);
        }
//        encode
        String equipEncodeTrim = StrUtil.trim(equipTransferDto.getEncode());
        if (StrUtil.isBlank(equipEncodeTrim)) {equipTransferDto.setEncode(null);}
        else {
            equipTransferDto.setEncode(equipEncodeTrim);
        }
//        sendingProject
        String equipSendingProjectTrim = StrUtil.trim(equipTransferDto.getSendingProject());
        if (StrUtil.isBlank(equipSendingProjectTrim)) {equipTransferDto.setSendingProject(null);}
        else {
            equipTransferDto.setSendingProject(equipSendingProjectTrim);
        }
//        receivingProject
        String receivingProjectTrim = StrUtil.trim(equipTransferDto.getReceivingProject());
        if (StrUtil.isBlank(receivingProjectTrim)) {equipTransferDto.setReceivingProject(null);}
        else {
            equipTransferDto.setReceivingProject(receivingProjectTrim);
        }
//        description
        String description = StrUtil.trim(equipTransferDto.getDescription());
        if (StrUtil.isBlank(description)) {equipTransferDto.setDescription(null);
        }
        return equipTransferDto;
    }

    public boolean fileOperation(String encode, MultipartFile[] eqPhotoList, HttpServletRequest request) {

//        创建一个equipmentPhotoDto集合作为向数据库写数据的容器
        List<EquipTransferPhotoDto> equipTransferPhotoList = new ArrayList<>();
//        创建日期目录
        String format = sdf.format(new Date());
//        详细目录名是date,存储equipTransferPhoto的目录，日期目录，encode目录
        String realPath = fileLocation + equipTransferPhotoPath + format + encode;
//        创建文件对象
        File folder = new File(realPath);
//        定义全网络路径
        String url;
//        创建目录
        if (!folder.exists()) {
            folder.mkdirs();
        }
//        把前端传进来的文件列表遍历，并写进硬盘中，同时写入数据库中
        for (MultipartFile multipartFile : eqPhotoList) {
            EquipTransferPhotoDto equipTransferPhotoDto=new EquipTransferPhotoDto();
//            获取文件的原始文件名，并取得文件后缀名，如.jpg
            String originalFilename = multipartFile.getOriginalFilename();
            int i = 0;
            if (originalFilename != null) {
                i = originalFilename.lastIndexOf(".");
            }
            String substring;
            String newFileName = null;
            if (originalFilename != null) {
//             把截取文件名的后缀  “.jpg”
                substring = originalFilename.substring(i).toLowerCase();
//            重新拼接文件名加.jpg，前缀是登录名，如登录名为eric，整照片的全名就是eric.jpg
//            为避免文件名出行由于菜单名称相同，而相同造成覆盖，采用了一个7位的随机字符串拼接
                newFileName = RandomUtil.randomString(4).toUpperCase() +substring;
//            }
                try {
//                    通过transferTo方法，把文件写入磁盘
                    multipartFile.transferTo(new File(folder, newFileName));





//                    拼接全网络文件路径
                    url = equipTransferPhotoPath+ format +encode+"/"+ newFileName;
//                    把url,encode,equipmentPhotoDto写入equipmentPhotoDto对象相应字段中








                    equipTransferPhotoDto.setPhotoUrl(url);
                    equipTransferPhotoDto.setEquipTransferEncode(encode);
                    equipTransferPhotoList.add(equipTransferPhotoDto);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
//        把equipmentPhotoDto列表转换为equipmentPhoto列表
        List<EquipTransferPhoto> transferPhotoList = BeanUtil.copyToList(equipTransferPhotoList, EquipTransferPhoto.class);
//        写入数据库
        return equipTransferPhotoService.saveBatch(transferPhotoList);
    }





    /******************************下面方法暂时不用***********************************/
/*
    //    todo 这个方法暂时作废
    @Override
    @Transactional
    public SaResult deleteByIdsService(ArrayList<Integer>ids) {
        if (ids == null) {
            return SaResult.error("id数组不能为空");
        }
        for (Integer id : ids) {
            //        联表删除
            DeleteJoinWrapper<EquipTransfer>wrapper= JoinWrappers.delete(EquipTransfer.class)
                    .deleteAll()
                    .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode)
                    .eq(EquipTransfer::getId,id);
            boolean b = deleteJoin(wrapper);

        }
        return SaResult.ok("succeed");
    }

//    这个方法不用

    @Override
    public SaResult getByCreateTimeService(Date createTime, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
//        当前端传来的是Date格式日期数据时，由于springMvc正常情况下是无法解析Date数据，需要转换，所以在controller的参数列表中
//       在Date参数前要加注解@DateTimeFormat(iso=DateTimeFormat.ISO.DATE)，看下面：
//        (@DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date createTime, Integer current, Integer pageSize)
//        把前端传来的时间格式化为指定格式，这里指定格式是timeFormat模式，即在类中公共字段
//        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = timeFormat.format(createTime);
//        创建分页对象
        Page<EquipTransferDto>page=new Page<>(current,pageSize);

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
//        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
//                记住，create_time前要加一个t.否则后面连接查询时，equip_transfer表和equip_transfer_photo表中都有create_time，会致使字段模糊，搞不清楚是那个表的create_tiem
//                这个是查指定日期的中的数据
                .apply("date_format(t.create_time,'%y%m%dd')=" + "date_format('" + format + "','%y%m%dd')")
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
//                下面的都是分页连接查询的普通步骤了
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);

    }

    //    这个方法不用
    @Override
    public SaResult getByUpdateTimeService(Date updateTime, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String format = timeFormat.format(updateTime);

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

//        创建分页对象
        Page<EquipTransferDto>page=new Page<>(current,pageSize);
//        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
//                记住，create_time前要加一个t.否则后面连接查询时，equip_transfer表和equip_transfer_photo表中都有create_time，会致使字段模糊，搞不清楚是那个表的create_tiem
//                这个是查指定日期的中的数据
                .apply("date_format(t.update_time,'%y%m%dd')=" + "date_format('" + format + "','%y%m%dd')")
//                下面的都是分页连接查询的普通步骤了
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);
    }

    //    这个方法不用
    @Override
    public SaResult getByReceivingProjectService(String projectName, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(projectName))){
            return SaResult.error("项目名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        Page<EquipTransferDto>page=new Page<>(current,pageSize);
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        //        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("receiving_project",projectName)
//                下面的都是分页连接查询的普通步骤了
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);
    }

    //    这个方法不用
    @Override
    public SaResult getByEqNameService(String equipName, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(equipName))){
            return SaResult.error("设备名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        Page<EquipTransferDto>page=new Page<>(current,pageSize);

        //        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("eq_name",equipName)
//                下面的都是分页连接查询的普通步骤了
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);
    }

    //    这个方法不用
    @Override
    public SaResult getByLastUpdateByService(String lastByName, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(lastByName))){
            return SaResult.error("人名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        Page<EquipTransferDto>page=new Page<>(current,pageSize);

        //        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("last_update_by",lastByName)
//                下面的都是分页连接查询的普通步骤了
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);
    }

    //    这个方法不用
    @Override
    public SaResult getByCreateByService(String createByName, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(createByName))){
            return SaResult.error("人名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        Page<EquipTransferDto>page=new Page<>(current,pageSize);

        //        创建查询条件对象
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
                .like("create_by",createByName)
//                下面的都是分页连接查询的普通步骤了
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);
    }

    //    这个方法不用
    @Override
    public SaResult getAllByMoon(Date moonDate, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String format = timeFormat.format(moonDate);
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

//        创建分页对象
        Page<EquipTransferDto>page=new Page<>(current,pageSize);
        MPJLambdaWrapper<EquipTransfer>wrapper=new MPJLambdaWrapper<EquipTransfer>()
                .selectAll(EquipTransfer.class)
//                记住，create_time前要加一个t.否则后面连接查询时，equip_transfer表和equip_transfer_photo表中都有create_time，会致使字段模糊，搞不清楚是那个表的create_tiem
//                这个是查指定日期的中的数据
//                queryWrapper.apply(" date_format(create_at,'%y%mm%') = date_format('" + withdrawRecord.getCreateAt() + "-01','%y%mm%')");

                .apply("date_format(t.create_time,'%y%m%')=" + "date_format('" + format + "','%y%m%')")
//                下面的都是分页连接查询的普通步骤了
                .eq(PublicTools.checkLoginRole(),EquipTransfer::getSendingProject,locationAddress)
                .selectCollection(EquipTransferPhoto.class,EquipTransferDto::getEquipTransferPhotoList)
                .leftJoin(EquipTransferPhoto.class,EquipTransferPhoto::getEquipTransferEncode,EquipTransfer::getEncode);
        Page<EquipTransferDto> equipTransferDtoPage = selectJoinListPage(page, EquipTransferDto.class, wrapper);
        List<EquipTransferDto> records = equipTransferDtoPage.getRecords();
        List<EquipTransferDto> equipTransferDtoList = BeanUtil.copyToList(records, EquipTransferDto.class);
        return SaResult.data(equipTransferDtoList);

    }
*/
    /******************************下面方法暂时不用***********************************/


}
